import React, {useEffect} from 'react';
import {useFocusEffect} from '@react-navigation/native';
import {
    Alert, BackHandler,
    Dimensions,
    Image, Keyboard, Modal,
    SafeAreaView,
    TextInput,
    ToastAndroid,
    TouchableOpacity,
    TouchableWithoutFeedback,
    View
} from "react-native";
import { StyleSheet } from 'react-native';
import {
    Button,
    Card,
    Divider,
    Icon,
    Input,
    Layout, List, Menu, MenuItem, OverflowMenu, Radio, RadioGroup,
    Tab,
    TabView,
    Text, Tooltip,
    TopNavigation,
    TopNavigationAction
} from '@ui-kitten/components';
import SorageManager from "../Compoments/SorageManager";
import {showMessage} from "react-native/Libraries/Utilities/LoadingView";
import AsyncStorage from "@react-native-async-storage/async-storage";


export const RepairCompletScreen = ({ navigation }) => {


    const [visible, setVisible] = React.useState(false);
    const [tabselectedIndex, setTabelectedIndex] = React.useState(null);

    const [undoList,setUndoList] = React.useState( []);
    const [hasDoneList,setHasDoneList] = React.useState( []);
    const [fixItemList,setFixItemList] = React.useState( []);

    const onItemSelect = (index) => {
        setSelectedIndex(index);
        setVisible(false);
    };




    //--------------------fetch  api -----------------------//

    /**
     * 获取未完成的
     * @param rkid
     */
    const qualityAdopt= (rkid,ch)=>{
        const  requestOptions = {
            method: 'GET',
            redirect: 'follow'
        };
        SorageManager.get('userInf').then(r =>{
            const url ="http://htjoa.nrnet.cn/dc14/jwmis/ticketController/continue?rkid="+rkid+"&wxr="+r["userid"]+"&jrd="+r["belongduan"]+"&ch="+ch
            console.log(url)
            fetch(url, requestOptions)
                .then(response => response.json())
                .then(result => {
                    console.log(result,"未完成")
                    setUndoList(result)

                })
                .catch(error => console.log('error', error));
        } )


    }


    /**
     * 获取已完成的
     * @param rkid
     */
    const getDone= (rkid,ch)=>{
        const  requestOptions = {
            method: 'GET',
            redirect: 'follow'
        };
        SorageManager.get('userInf').then(r =>{
            fetch("http://htjoa.nrnet.cn/dc14/jwmis/ticketController/done?rkid="+rkid+"&wxr="+r["userid"]+"&jrd="+r["belongduan"]+"&ch="+ch, requestOptions)
                .then(response => response.json())
                .then(result => {
                    console.log(result,"已完成")
                    setHasDoneList(result)

                })
                .catch(error => console.log('error', error));
        } )


    }


    /**
     * 获取维修项目
     * @param id
     */
    const getFixItem = (hid,id,rkid,wxr)=>{
        const requestOptions = {
            method: 'GET',
            redirect: 'follow'
        };
        const url = "http://htjoa.nrnet.cn/dc14/jwmis/repairController/repair?fault="+hid
        console.log(url)
        fetch(url, requestOptions)
            .then(response => response.json())
            .then(result => {
                console.log(result,"获取维修方式")
                setFixItemList(result)
                navigation.navigate('SelectFixItem',{result:result,id:id,rkid:rkid,wxr:wxr});
                // setVisible(true)
            })
            .catch(error => console.log('error', error));
    }

    /**
     * 完成按钮
     * @param bz => 备注
     * @param wxwcfs
     * @param id
     */
    const acceptFix = (bz,wxwcfs,id)=>{
        const requestOptions = {
            method: 'GET',
            redirect: 'follow'
        };

        fetch("http://htjoa.nrnet.cn/dc14/jwmis/acceptancerepair/repairdonebyid?bz&wxwcfs="+wxwcfs+"&j28=已处理&id="+id, requestOptions)
            .then(response => response.text())
            .then(result => {
                console.log(result,"完成按钮")
                if (result === 'success'){
                    setVisible(false)
                    SorageManager.get("search2").then(s=>{
                        if (s===undefined){
                            qualityAdopt('','')
                        }

                        qualityAdopt('',s)
                    })


                }


            })
            .catch(error => console.log('error', error));
    }


    useEffect(()=>{

        Keyboard.addListener("keyboardDidHide", _keyboardDidHide);


        SorageManager.set("search2",'')

        SorageManager.get("search2").then(s=>{
            if (s === undefined ){
                qualityAdopt('','')
                getDone('','')
            }
            else {
                qualityAdopt('',s)
                getDone('',s)
            }
        })


        // cleanup function
        return () => {
            Keyboard.removeListener("keyboardDidHide", _keyboardDidHide);
        };


    },[])


    // //监听页面返回 刷新数据


    useFocusEffect(React.useCallback(() => {
        Keyboard.addListener("keyboardDidHide", _keyboardDidHide);

        console.log('页面再次刷新');
        SorageManager.get("search2").then(s=>{
            if (s === undefined ){
                qualityAdopt('','')
                getDone('','')
            }
            else {
                qualityAdopt('',s)
                getDone('',s)
            }
        })


        // cleanup function
        return () => {
            Keyboard.removeListener("keyboardDidHide", _keyboardDidHide);
        };

    }, []));


    //监听键盘事件，缩回根据 搜索框内容重新加载
    const _keyboardDidHide = async () => {
       const  s =  await AsyncStorage.getItem("search2")
        if (s === undefined || s === null) {
            qualityAdopt('', '')
            getDone('', '')
        } else {
            qualityAdopt('', s)
            getDone('', s)
        }

    };

    //
    //     useFocusEffect(
    //         React.useCallback(() => {
    //             return () => {
    //                 qualityAdopt('','')
    //                 getDone('','')
    //             };
    //         }, [])
    //     );




    const navigateSelectFixItemScreen = () => {

    };



    const renderItemHeader = (headerProps, info) => (
        <View {...headerProps} style={{alignItems: 'center',margin:10}}>
            <Text category='h6' >
                车型： {info.item.firstname}        车号： {info.item.ch}
            </Text>
        </View>
    );




    const renderItemFooter = (footerProps,info) => (



        <View>

            <Button onPress={() => {
                getFixItem(info.item.hid,info.item.id,info.item.rkid,info.item.wxr)


            }}>
                完成
            </Button>

            <Modal
                visible={visible}
                backdropStyle={styles.backdrop}
                onBackdropPress={() => setVisible(false)}>
                <Card style={{marginTop: 200}} disabled={true}>
                    <Text>请选择维修方式：</Text>

                    <RadioGroup
                        selectedIndex={selectedIndex}
                        onChange={index => setSelectedIndex(index)}>
                        {fixItemList.map((item,index)=>{
                            return(
                                <Radio>
                                    {item["operMethod"]}
                                </Radio>
                            )
                        })}
                    </RadioGroup>

                   <Button  onPress={()=>{
                       acceptFix('',fixItemList[selectedIndex]["id"],info.item.id,)
                   }}>
                       提交
                   </Button>
                    <Button style={{marginTop:10}} onPress={() => setVisible(false)}
                            appearance='outline'
                            status='warning'
                    >
                        返回
                    </Button>
                </Card>
            </Modal>

        </View>

    );

    const renderItem = (info) => (
        <Card
            style={styles.item}
            status='basic'
            header={headerProps => renderItemHeader(headerProps, info)}
            footer={footerProps => renderItemFooter(footerProps, info)}>
            <Layout style={styles.textContainer}>
                <Layout style={styles.textItem}>
                    <Text>
                        领取时间: {info.item.wxlqrq}
                    </Text>
                </Layout>

            </Layout>


            <Layout style={styles.textContainer}>
                <Layout style={styles.textItem}>
                    <Text>
                        故障名称：
                    </Text>
                </Layout>
                <Layout style={styles.textItem}>
                    <Text>
                        {info.item.gzxx}
                    </Text>
                </Layout>

            </Layout>





        </Card>
    );


    const accept = (info) => (
        <Card
            style={styles.item}
            status='success'
            header={headerProps => renderItemHeader(headerProps, info)}
          >




            <Layout style={styles.textContainer}>
                <Layout style={styles.textItem}>
                    <Text>
                        领活时间:{info.item.hxtqsj}
                    </Text>
                </Layout>
            </Layout>
            <Layout style={styles.textContainer}>
                <Layout style={styles.textItem}>
                    <Text>
                        完成时间: {info.item.wxwcrq}
                    </Text>
                </Layout>

                {/*<Layout style={styles.textItem}>*/}
                {/*    <Text>*/}
                {/*        范围:0*/}
                {/*    </Text>*/}
                {/*</Layout>*/}
                {/*<Layout style={styles.textItem}>*/}
                {/*    <Text>*/}
                {/*        动态:0*/}
                {/*    </Text>*/}
                {/*</Layout>*/}
            </Layout>

            <Layout style={styles.textContainer}>
                <Layout style={styles.textItem}>
                    <Text>
                        故障名称：
                    </Text>
                </Layout>
                <Layout style={styles.textItem}>
                    <Text>
                        {info.item.gzxx}
                    </Text>
                </Layout>

                <Layout style={styles.textContainer}>
                    <Layout style={styles.textItem}>
                        <Text>
                            维修方式: {info.item.operMethod}
                        </Text>
                    </Layout>
                </Layout>

                    <Layout style={styles.textItem}>
                        <Text>
                            未通过原因: 无
                        </Text>
                    </Layout>

            </Layout>


        </Card>
    );



    const renderacceptFooter = (footerProps) => (
        <Button appearance='outline' status='warning' onPress={deleteButton}>
            取消
        </Button>
    );


    // const BackIcon = (props) => (
    //     <Icon {...props} name='arrow-back' />
    // );
    // const navigateBack = () => {
    //     navigation.goBack();
    // };
    // const BackAction = () => (
    //     <TopNavigationAction icon={BackIcon} onPress={navigateBack}/>
    // );

    const BackIcon = (props) => (
        <Icon {...props} name='arrow-back'/>
    );

    const navigateMenu = () => {
        navigation.navigate('Menu');
    };

    const BackAction = () => (
        <TopNavigationAction icon={BackIcon} onPress={navigateMenu}/>
    );

    const [selectedIndex, setSelectedIndex] = React.useState(0);
    const [value, setValue] = React.useState('');
    return (
        <View style={{ flex: 1 }}>
            <TopNavigation
                accessoryLeft={BackAction}
                title='施修结束' alignment='center' />
            <Divider/>
            <TabView
                selectedIndex={tabselectedIndex}
                onSelect={async index => {
                    setTabelectedIndex(index)
                    const s = await AsyncStorage.getItem("search2")
                    if (s === undefined  || s === null) {
                        qualityAdopt('', '')
                        getDone('', '')
                    } else {
                        qualityAdopt('', s)
                        getDone('', s)
                    }
                }


            }>
                <Tab title='未完成'>
                    <Layout style={styles.tabContainer}>


                        <View style={{flexDirection:'row',justifyContent: 'center',marginTop:10,marginBottom:10}}>

                            <Input
                                style={{width:Dimensions.get('window').width-20}}
                                value={value}
                                placeholder='机车号模糊查找'
                                accessoryRight={(<Icon
                                    onPress={()=> {
                                            qualityAdopt('','')
                                            getDone('','')
                                            SorageManager.set("search2",'')
                                            ToastAndroid.show("取消查询", ToastAndroid.SHORT);
                                            setValue('')

                                        // SorageManager.get("search2").then(s=>{
                                        //     console.log(r,"userINf")
                                        //     qualityAdopt('','')
                                        //     getDone('','')
                                        //     SorageManager.set("Search2",'')
                                        //     ToastAndroid.show("取消查询", ToastAndroid.SHORT);
                                        //     setValue('')
                                        // })
                                    }
                                    }
                                    style={styles.icon}
                                    fill='#8F9BB3'
                                    name='close-outline'
                                />)}
                                // secureTextEntry={secureTextEntry}
                                onChangeText={async nextValue => {
                                    setValue(nextValue);
                                    console.log(nextValue, "存储值")
                                    console.log(typeof nextValue)
                                    await AsyncStorage.setItem("search2", nextValue)

                                }}
                            />

                            {/*<Input*/}
                            {/*       placeholder='机车号'*/}
                            {/*       value={value}*/}
                            {/*       onChangeText={nextValue => setValue(nextValue)}>*/}
                            {/*</Input>*/}

                        </View>

                        <Divider/>
                        <List
                            style={styles.container}
                            contentContainerStyle={styles.contentContainer}
                            data={undoList}
                            renderItem={renderItem}
                        />

                    </Layout>
                </Tab>

                <Tab title='已完成'>
                    <Layout style={styles.tabContainer}>
                        <List
                            style={styles.container}
                            contentContainerStyle={styles.contentContainer}
                            data={hasDoneList}
                            renderItem={accept}
                        />

                    </Layout>
                </Tab>
            </TabView>



            {/*<OverflowMenu*/}
            {/*    anchor={renderToggleButton}*/}
            {/*    backdropStyle={styles.backdrop}*/}
            {/*    visible={visible}*/}
            {/*    selectedIndex={selectedIndex}*/}
            {/*    onSelect={onItemSelect}*/}
            {/*    onBackdropPress={() => setVisible(false)}>*/}

            {/*    <MenuItem title='Orders'/>*/}
            {/*    <MenuItem title='Transactions'/>*/}
            {/*    <MenuItem title='Users'/>*/}
            {/*    <MenuItem title='Orders'/>*/}
            {/*    <MenuItem title='Transactions'/>*/}
            {/*</OverflowMenu>*/}


        </View>
    );
};

const styles = StyleSheet.create({
    container: {
        minHeight: 144,
    },
    contentContainer: {
        paddingHorizontal: 15,
        // paddingVertical: 4,
    },
    item: {
        marginTop:15,
        // marginVertical: 4,

    },

    tabContainer: {
        height: Dimensions.get('window').height-118,
    },

    textContainer:{
        flexDirection:'row',
        flexWrap:'wrap',
        justifyContent:"space-evenly",
        alignItems:"center",
        marginBottom:10

    },
    textItem:{
        justifyContent:'center',
        alignItems:'center',

    },

    backdrop: {
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
    },
});